package rsj.dao;

import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import rsj.db.dbutils.UniqueID;

import java.sql.Connection;
import java.sql.Timestamp;

public class ProdCollDao extends BaseDao{
    private static final  ProdCollDao instance = new ProdCollDao();
    public static  ProdCollDao getInstance() {
        return instance;
    }

    private static final String tableName = "sys.sys_prco";
    private static final String allColumns = "prco_id,prco_org_id,prco_prod_id,prco_collect,prco_prod_name,prco_utime";

    public int insert(MapNode data, String prodName) {
        String orgId = data.getValue("Org_Id");
        String prodId = data.getValue("Prod_Id");
        String collStatus = data.getValue("Coll_Status");


        return (int)invokeSql(conn -> {
            TableNode prodCollList = selectByOrgProd(orgId, prodId, conn);

            // 产品收藏
            if(prodCollList.toList() == null || prodCollList.toList().size() == 0){
                String sql = String.format(insertSql, tableName, allColumns, "?,?,?,?,?,?");
                return getQueryRunner().update(conn, sql, UniqueID.generateId(),
                        orgId, prodId, collStatus, prodName, new Timestamp(System.currentTimeMillis()));
            }
            // 产品取消收藏
            else {
                String sql = String.format(updateSql, tableName, " prco_collect = ?, prco_utime = ?", " prco_org_id = ? and prco_prod_id = ? ");
                return getQueryRunner().update(conn, sql, collStatus
                        , new Timestamp(System.currentTimeMillis())
                        ,orgId, prodId);
            }
        });
    }

    private TableNode selectByOrgProd(String orgId, String prodId, Connection conn) {
        String sqlTemp = "select %s from %s where %s ";
        String sql = String.format(sqlTemp, allColumns, tableName, " prco_org_id = ? and prco_prod_id = ? ");
        return getQueryRunner().queryLinkTableNode(conn, sql, orgId, prodId);
    }
}
